package com.shadow.baiqun.delegate.room.change;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.rey.material.widget.Spinner;
import com.shadow.baiqun.R;
import com.shadow.baiqun.R2;
import com.shadow.baiqun.config.ItemField;
import com.shadow.baiqun.delegate.common.ResultConverter;
import com.shadow.baiqun.delegate.room.check.BoardInfoEntity;
import com.shadow.baiqun.event.ScanInfoEvent;
import com.shadow.baiqun.global.GlobalDataManager;
import com.shadow.baiqun.global.LocationEntity;
import com.shadow.core.delegate.RxShadowDelegate;
import com.shadow.core.net.callback.IError;
import com.shadow.core.net.callback.ISuccess;
import com.shadow.core.net.rx.RxRestClient;
import com.shadow.core.util.toast.ToastUtils;
import com.shadow.ui.recycler.MultipleItemEntity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author zy
 * on 2018/7/13
 * 提交变更
 */
public class ChangeTaskCommitDelegate extends RxShadowDelegate {
    private static final String ENTITY = "entity";

    public static ChangeTaskCommitDelegate create(BoardInfoEntity boardInfoEntity) {
        final ChangeTaskCommitDelegate contentDelegate = new ChangeTaskCommitDelegate();
        final Bundle bundle = new Bundle();
        bundle.putSerializable(ENTITY, boardInfoEntity);
        contentDelegate.setArguments(bundle);
        return contentDelegate;
    }

    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.et_part_name)
    TextView mTvPartName;
    @BindView(R2.id.et_part_code)
    TextView mTvCode;
    @BindView(R2.id.spinner_state)
    Spinner mSpState;
    @BindView(R2.id.spinner_station)
    Spinner mSpStation;
    private int mCurrentStateId = 1;
    private String mCurrentDepId;

    private BoardInfoEntity mBoardInfoEntity;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mBoardInfoEntity = ((BoardInfoEntity) bundle.getSerializable(ENTITY));
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_change_task_commit;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pop();
                }
            });
            mToolbar.setTitle("变更");
        }
        try {
            mTvPartName.setText(mBoardInfoEntity.getPartName());
            mTvCode.setText(mBoardInfoEntity.getPartNum());
            initSpState();
            initSpStation();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initSpState() {
        List<String> items = new ArrayList<>();
        items.add("良品");
        items.add("不良品");
        items.add("待检品");
        items.add("隔离品");
        items.add("特殊零件优先发货");
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.row_spn, items);
        adapter.setDropDownViewResource(R.layout.row_spn_dropdown);
        int defaultStatus = mBoardInfoEntity.getStockStatus();

        mSpState.setAdapter(adapter);
        mSpState.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
            @Override
            public void onItemSelected(Spinner parent, View view, int position, long id) {
                mCurrentStateId = position + 1;
            }
        });
        if (defaultStatus > 0 && defaultStatus < items.size() + 1) {
            mSpState.setSelection(defaultStatus - 1);
            mCurrentStateId = defaultStatus;
        }
    }

    private void initSpStation() {
        List<String> items = new ArrayList<>();
        final List<MultipleItemEntity> locationList = GlobalDataManager.getInstance().getLocationEntityList();
        if (locationList != null && !locationList.isEmpty()) {
            int currentPosition = 0;
            for (int i = 0, size = locationList.size(); i < size; i++) {
                MultipleItemEntity multipleItemEntity = locationList.get(i);
                LocationEntity entity = multipleItemEntity.getField(ItemField.ITEM_OBJ);
                if (entity != null) {
                    if (mBoardInfoEntity.getPrepgoodsCStock().equals(entity.getDepotName())) {
                        currentPosition = i;
                        mCurrentDepId = entity.getDepotId();
                    }
                    items.add(entity.getDepotName());
                }
            }
            ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.row_spn, items);
            adapter.setDropDownViewResource(R.layout.row_spn_dropdown);
            mSpStation.setAdapter(adapter);
            mSpStation.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
                @Override
                public void onItemSelected(Spinner parent, View view, int position, long id) {
                    MultipleItemEntity multipleItemEntity = locationList.get(position);
                    LocationEntity entity = multipleItemEntity.getField(ItemField.ITEM_OBJ);
                    mCurrentDepId = entity.getDepotId();
                }
            });
            mSpStation.setSelection(currentPosition);
        }
    }

    @OnClick(R2.id.tv_commit)
    public void onCommit() {
        mDisposables.add(RxRestClient.builder()
                .loader(getContext())
                .url("WMS/backstage/indoorChange/changeAct")
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        int code = new ResultConverter().getCode(response);
                        if (code == 0) {
                            ToastUtils.showToast(getContext(), "提交成功!数据未修改");
                            pop();
                        } else if (code > 0) {
                            ToastUtils.showToast(getContext(), "提交成功!等待打印标签");
                            pop();
                        } else if (code == -2) {
                            ToastUtils.showToast(getContext(), "该条记录已经操作过,不能再执行!");
                        } else {
                            ToastUtils.showToast(getContext(), "提交失败!");
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        ToastUtils.showToast(getContext(), msg);
                    }
                })
                .params("stu", mCurrentStateId)
                .params("depotid", mCurrentDepId)
                .params("actType", 1)
                .params("id", mBoardInfoEntity.getId())
                .params("tagid", mBoardInfoEntity.getTabId())
                .build()
                .unRestGet());
    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(priority = 1)
    public void scanEvent(ScanInfoEvent event) {
        //接收了该事件就拦截掉 不会继续往优先级小于priority的地方传递
        EventBus.getDefault().cancelEventDelivery(event);
    }
}
